package com.dhj;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

/**
 * @author DaHuaJia
 * @Description httpClient 连接池
 * @Date 2021-11-13 12:05:41
 */
public class HttpPoolTest {

    public static void main(String[] args) throws Exception {
        // 创建连接池管理器
        PoolingHttpClientConnectionManager clientPool = new PoolingHttpClientConnectionManager();

        // 设置最大连接数
        clientPool.setMaxTotal(100);

        // 设置每个主机的最大连接数，即同一个IP或域名的最大连接数
        clientPool.setDefaultMaxPerRoute(10);

        // 使用连接池管理器发起请求
        doGet(clientPool);
        doPost(clientPool);
    }

    /**
     * 使用连接池管理器发送GET请求
     *
     * @param clientPool 连接池管理器
     */
    private static void doGet(PoolingHttpClientConnectionManager clientPool) throws Exception {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(clientPool).build();

        HttpGet httpGet = new HttpGet("https://www.baidu.com");

        CloseableHttpResponse response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() == 200) {
            String content = EntityUtils.toString(response.getEntity());
            System.out.println(content);
        }

        if (response != null) {
            response.close();
        }

        // 不能关闭HttpClient，由连接池管理器进行管理
    }


    /**
     * 使用连接池管理器发送POST请求
     *
     * @param clientPool 连接池管理器
     */
    private static void doPost(PoolingHttpClientConnectionManager clientPool) throws Exception {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(clientPool).build();

        HttpPost httpPost = new HttpPost("https://www.baidu.com");

        CloseableHttpResponse response = httpClient.execute(httpPost);

        if (response.getStatusLine().getStatusCode() == 200) {
            String content = EntityUtils.toString(response.getEntity());
            System.out.println(content);
        }

        if (response != null) {
            response.close();
        }

        // 不能关闭HttpClient，由连接池管理器进行管理
    }


}
